<?php
    defined('INDEX') or die ('Acesso direto n&atilde;o permitido');
    
    class SessionManager
    {
        public function __construct()
        {
            if(!isset($_SESSION))
            {
            	session_start();
            }
        }
        
        /**
         * Returns the stored message in the user session.
         * 
         * @return stdClass $content - the stored object.
         */
        public function getStoredMessage ()
        {
            return isset($this->getSession()->stored_message) ? $this->getSession()->stored_message : null;
        }
        
        /**
         * Destroy all stored messages of user session.
         * 
         * @return void
         */
        public function destroyStoredMessage ()
        {
            $this->getSession()->stored_message = null;
        }
        
        /**
         * This function store an stdClass object in the user session.
         * 
         * @param stdClass $content
         * 
         * @return bool $ok - true if can store.
         */
        public function storeMessage (stdClass $content)
        {
            if($this->hasSession())
            {
                $_SESSION['app']->stored_message = $content;
                return true;
            }
            else
            {
                return false;
            }
        }
        
        /**
         * Checks if exists an stored message object in the user session.
         * 
         * @return bool $has - true when have messages.
         */
        public function hasStoredMessage()
        {
            if($this->hasSession())
            {
                return is_object($this->getSession()->stored_message);
            }
            else
            {
                return false;
            }
        }
        
        public function getSession()
        {
            return $this->hasSession() ? ((object) $_SESSION['app']) : null;
        }
        
        public function hasSession()
        {
            return (isset($_SESSION['app']) && is_object($_SESSION['app']));
        }
        
        public function createSession(stdClass $content, $override = false)
        {
            if(!$this->hasSession() || ($this->hasSession() && $override) )
            {
                $content->data_criacao     = time();
                $content->stored_message   = null;
                
                $_SESSION['app']           = $content;
                
                return true;
            }
            else
            {
                return false;
            }
        }
        
        public function destroySession ()
        {
            $_SESSION['app'] = null;
            unset($_SESSION['app']);
            
            return true;
        }
    }
?>